Goal for the project is to Predict whether a client will subscribe (yes / no) to a term deposit, this based on data from a Portuguese bank’s direct marketing campaigns conducted via phone calls.
The dataset is structured and suitable for models like Logistic Regression, LDA, QDA, KNN, Random Forest, and others.
data <- read.csv("./bank-full.csv", header = TRUE, sep = ";", stringsAsFactors = TRUE)
bank <- data |> rename(subscribed = y)
num_rows <- nrow(bank)
num_cols <- ncol(bank) - 1
data_summary <- data.frame(
Characteristic = c("Number of Rows", "Number of Columns", "Number of Predictors", "Target Variable"),
Value = c(num_rows, num_cols, num_cols, "subscribed")
)
print(data_summary)
## Characteristic Value
## 1 Number of Rows 45211
## 2 Number of Columns 16
## 3 Number of Predictors 16
## 4 Target Variable subscribed
summary(bank)
## age job marital education
## Min. :18.00 blue-collar:9732 divorced: 5207 primary : 6851
## 1st Qu.:33.00 management :9458 married :27214 secondary:23202
## Median :39.00 technician :7597 single :12790 tertiary :13301
## Mean :40.94 admin. :5171 unknown : 1857
## 3rd Qu.:48.00 services :4154
## Max. :95.00 retired :2264
## (Other) :6835
## default balance housing loan contact
## no :44396 Min. : -8019 no :20081 no :37967 cellular :29285
## yes: 815 1st Qu.: 72 yes:25130 yes: 7244 telephone: 2906
## Median : 448 unknown :13020
## Mean : 1362
## 3rd Qu.: 1428
## Max. :102127
##
## day month duration campaign
## Min. : 1.00 may :13766 Min. : 0.0 Min. : 1.000
## 1st Qu.: 8.00 jul : 6895 1st Qu.: 103.0 1st Qu.: 1.000
## Median :16.00 aug : 6247 Median : 180.0 Median : 2.000
## Mean :15.81 jun : 5341 Mean : 258.2 Mean : 2.764
## 3rd Qu.:21.00 nov : 3970 3rd Qu.: 319.0 3rd Qu.: 3.000
## Max. :31.00 apr : 2932 Max. :4918.0 Max. :63.000
## (Other): 6060
## pdays previous poutcome subscribed
## Min. : -1.0 Min. : 0.0000 failure: 4901 no :39922
## 1st Qu.: -1.0 1st Qu.: 0.0000 other : 1840 yes: 5289
## Median : -1.0 Median : 0.0000 success: 1511
## Mean : 40.2 Mean : 0.5803 unknown:36959
## 3rd Qu.: -1.0 3rd Qu.: 0.0000
## Max. :871.0 Max. :275.0000
##
str(bank)
## 'data.frame': 45211 obs. of 17 variables:
## $ age : int 58 44 33 47 33 35 28 42 58 43 ...
## $ job : Factor w/ 12 levels "admin.","blue-collar",..: 5 10 3 2 12 5 5 3 6 10 ...
## $ marital : Factor w/ 3 levels "divorced","married",..: 2 3 2 2 3 2 3 1 2 3 ...
## $ education : Factor w/ 4 levels "primary","secondary",..: 3 2 2 4 4 3 3 3 1 2 ...
## $ default : Factor w/ 2 levels "no","yes": 1 1 1 1 1 1 1 2 1 1 ...
## $ balance : int 2143 29 2 1506 1 231 447 2 121 593 ...
## $ housing : Factor w/ 2 levels "no","yes": 2 2 2 2 1 2 2 2 2 2 ...
## $ loan : Factor w/ 2 levels "no","yes": 1 1 2 1 1 1 2 1 1 1 ...
## $ contact : Factor w/ 3 levels "cellular","telephone",..: 3 3 3 3 3 3 3 3 3 3 ...
## $ day : int 5 5 5 5 5 5 5 5 5 5 ...
## $ month : Factor w/ 12 levels "apr","aug","dec",..: 9 9 9 9 9 9 9 9 9 9 ...
## $ duration : int 261 151 76 92 198 139 217 380 50 55 ...
## $ campaign : int 1 1 1 1 1 1 1 1 1 1 ...
## $ pdays : int -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 ...
## $ previous : int 0 0 0 0 0 0 0 0 0 0 ...
## $ poutcome : Factor w/ 4 levels "failure","other",..: 4 4 4 4 4 4 4 4 4 4 ...
## $ subscribed: Factor w/ 2 levels "no","yes": 1 1 1 1 1 1 1 1 1 1 ...
This data-set contains no empty values at first sight.
colSums(is.na(bank))
## age job marital education default balance housing
## 0 0 0 0 0 0 0
## loan contact day month duration campaign pdays
## 0 0 0 0 0 0 0
## previous poutcome subscribed
## 0 0 0
numeric_vars <- names(bank)[sapply(bank, is.numeric)]
categorical_vars <- names(bank)[sapply(bank, function(x) is.factor(x) || is.character(x))]
cat("Numeric variables:\n")
## Numeric variables:
print(numeric_vars)
## [1] "age" "balance" "day" "duration" "campaign" "pdays" "previous"
cat("Categorical variables:\n")
## Categorical variables:
print(categorical_vars)
## [1] "job" "marital" "education" "default" "housing"
## [6] "loan" "contact" "month" "poutcome" "subscribed"
Visual confirmation for emptyness search, no data is missing in this data set
vis_miss(bank) +
labs(
title = "Visualizing Missing Data",
x = "",
y = ""
) +
theme(
plot.title = element_text(size = 8, face = "bold"),
plot.subtitle = element_text(size = 8),
axis.text.x = element_text(angle = 90, hjust = 1)
)
plt_subscribed <- bank |>
group_by(subscribed) |>
summarise(cnt = n()) |>
mutate(perc = round(cnt / sum(cnt), 4))
plt_prop <- ggplot(plt_subscribed, aes(x = subscribed, y = perc, colour = subscribed)) +
geom_bar(aes(fill = subscribed), show.legend = FALSE, stat = "identity") +
ylab("Proportion of Subscribed")
grid.arrange(grobs = list(tableGrob(plt_subscribed), plt_prop), ncol = 1)
categorical_vars_plt <- categorical_vars[categorical_vars != "subscribed"]
plt_categorical <- lapply(seq_along(categorical_vars_plt), function(i) {
ggplot(bank, aes_string(x = categorical_vars_plt[i], fill = "subscribed")) +
geom_bar(position = "fill") +
scale_y_continuous(labels = scales::percent) +
scale_fill_discrete() +
labs(title = paste("Subscription Rate by", categorical_vars_plt[i]),
y = "Proportion", x = NULL) +
coord_flip() +
theme(legend.position = if (i == 1) "bottom" else "none")
})
wrap_plots(plt_categorical, ncol = 3, guides = "collect") & theme(legend.position = "bottom")
plt_num <- lapply(numeric_vars, function(var) {
ggplot(bank, aes_string(x = "subscribed", y = var, fill = "subscribed")) +
geom_boxplot(alpha = 0.7) +
scale_fill_discrete() +
labs(title = paste("Dist. of", var, "by Subscribed"), y = var, x = NULL)
})
wrap_plots(plt_num, ncol = 3) & theme(legend.position = "none")
for_corr <- bank
for_corr$subscribed <- ifelse(bank$subscribed == "yes", 1, 0)
vars_corr <- names(for_corr)[sapply(for_corr, is.numeric)]
corr_df <- for_corr[vars_corr]
cor_matrix <- cor(corr_df, use = "complete.obs")
subscribed_cor <- cor_matrix[, "subscribed", drop = FALSE]
subscribed_cor <- subscribed_cor[order(abs(subscribed_cor[,1]), decreasing = TRUE), , drop = FALSE]
cor_df <- data.frame(
variable = rownames(subscribed_cor),
correlation = subscribed_cor[,1]
)
ggplot(cor_df, aes(x = reorder(variable, correlation), y = correlation)) +
geom_bar(stat = "identity", fill = "steelblue") +
coord_flip() +
labs(title = "Correlation with Subscribed", x = "Variable", y = "Correlation")
### PCA
for_pca <- bank
for_pca <- bank[sapply(data, is.numeric)]
pca <- prcomp(for_pca, scale. = TRUE)
autoplot(pca, data = bank, colour = 'subscribed', loadings = TRUE, loadings.label = TRUE) +
labs(title = "PCA")
loadings <- as.data.frame(pca$rotation)
loadings$variable <- rownames(loadings)
loadings$PC1.ABS <- abs(loadings$PC1)
loadings$PC2.ABS <- abs(loadings$PC2)
top_pc1 <- loadings[order(-loadings$PC1.ABS), c("variable", "PC1")][1:7, ]
top_pc2 <- loadings[order(-loadings$PC2.ABS), c("variable", "PC2")][1:7, ]
top_combined <- data.frame(
PC1_Variable = top_pc1$variable,
PC1_Loading = round(top_pc1$PC1, 3),
PC2_Variable = top_pc2$variable,
PC2_Loading = round(top_pc2$PC2, 3)
)
print(top_combined)
## PC1_Variable PC1_Loading PC2_Variable PC2_Loading
## 1 pdays 0.668 campaign 0.612
## 2 previous 0.641 day 0.512
## 3 day -0.271 duration -0.450
## 4 campaign -0.255 previous 0.288
## 5 duration 0.059 pdays 0.207
## 6 balance 0.029 balance -0.144
## 7 age -0.022 age -0.118
Principal Component Analysis (PCA) on the numeric variables revealed that pdays and previous contributed most to the first principal component (PC1), capturing variability related to past campaign exposure. The second component (PC2) was primarily influenced by campaign, day, and negatively by duration, reflecting variation in campaign intensity and contact timing.
We can interpret the components as:
eigenvals <- pca$sdev^2
plot(eigenvals / sum(eigenvals), type = "l", main = "Scree Plot", ylab = "Prop. Var. Explained", xlab = "PC #", ylim = c(0, 1))
cumulative.prop <- cumsum(eigenvals / sum(eigenvals))
lines(cumulative.prop, lty = 2)
eigenvals <- pca$sdev^2
prop_var <- eigenvals / sum(eigenvals)
cum_var <- cumsum(prop_var)
pc_table <- data.frame(
PC = paste0("PC", 1:length(prop_var)),
"Variance Explained" = round(prop_var, 4),
"Cumulative Variance" = round(cum_var, 4)
)
print(pc_table)
## PC Variance.Explained Cumulative.Variance
## 1 PC1 0.2156 0.2156
## 2 PC2 0.1650 0.3806
## 3 PC3 0.1567 0.5373
## 4 PC4 0.1393 0.6766
## 5 PC5 0.1282 0.8048
## 6 PC6 0.1180 0.9228
## 7 PC7 0.0772 1.0000
pca_scores <- as.data.frame(pca$x)
pca_scores$subscribed <- bank$subscribed
plot_ly(
data = pca_scores,
x = ~PC1, y = ~PC2, z = ~PC3,
color = ~subscribed,
colors = c("red", "deepskyblue"),
type = "scatter3d",
mode = "markers"
)
It appears that we’re missing a significant portion of the variance by focusing only on the numeric variables. PC1 and PC2 explain the most variation among these, but even after adding PC3, we don’t observe meaningful separation between subscription outcomes. This suggests that additional structure — possibly critical for understanding or predicting subscribed — may lie in the categorical variables, which were not included in this PCA.
Let’s understand a bit how the numerals contribute to explain the subscription
for_glm <- bank
for_glm$subscribed <- ifelse(for_glm$subscribed == "yes", 1, 0)
all_num_additive <- glm(subscribed ~ duration + pdays + previous + campaign + balance + age + day, data = for_glm, family = binomial)
summary(all_num_additive)
##
## Call:
## glm(formula = subscribed ~ duration + pdays + previous + campaign +
## balance + age + day, family = binomial, data = for_glm)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -3.470e+00 7.694e-02 -45.099 < 2e-16 ***
## duration 3.637e-03 5.642e-05 64.468 < 2e-16 ***
## pdays 2.114e-03 1.543e-04 13.698 < 2e-16 ***
## previous 8.594e-02 7.367e-03 11.666 < 2e-16 ***
## campaign -1.280e-01 9.583e-03 -13.361 < 2e-16 ***
## balance 3.718e-05 4.290e-06 8.668 < 2e-16 ***
## age 7.959e-03 1.472e-03 5.408 6.38e-08 ***
## day -1.650e-03 2.012e-03 -0.820 0.412
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 32631 on 45210 degrees of freedom
## Residual deviance: 26512 on 45203 degrees of freedom
## AIC: 26528
##
## Number of Fisher Scoring iterations: 6
tidy(all_num_additive, conf.int = TRUE) |>
filter(term != "(Intercept)") |>
ggplot(aes(x = reorder(term, estimate), y = estimate)) +
geom_point() +
geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = 0.1) +
coord_flip() +
labs(title = "Logistic Regression Coefficients",
y = "Estimate (log-odds)", x = "Variable")
Modeling with all categoricals might tell some story
bank_cat <- bank
cat_model_vars <- setdiff(categorical_vars, "subscribed")
model_glm_cat <- as.formula(paste("subscribed ~", paste(cat_model_vars, collapse = " + ")))
glm_cats <- glm(model_glm_cat, data = bank_cat, family = binomial)
summary(glm_cats)
##
## Call:
## glm(formula = model_glm_cat, family = binomial, data = bank_cat)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.24314 0.10655 -11.668 < 2e-16 ***
## jobblue-collar -0.12463 0.06490 -1.920 0.054810 .
## jobentrepreneur -0.19098 0.11110 -1.719 0.085610 .
## jobhousemaid -0.28256 0.11968 -2.361 0.018229 *
## jobmanagement -0.04708 0.06561 -0.718 0.473032
## jobretired 0.46521 0.07788 5.973 2.32e-09 ***
## jobself-employed -0.09070 0.09912 -0.915 0.360138
## jobservices -0.08616 0.07451 -1.156 0.247504
## jobstudent 0.33065 0.09770 3.384 0.000714 ***
## jobtechnician -0.06466 0.06187 -1.045 0.295971
## jobunemployed 0.13111 0.09768 1.342 0.179526
## jobunknown -0.19407 0.20780 -0.934 0.350347
## maritalmarried -0.20636 0.05158 -4.001 6.31e-05 ***
## maritalsingle 0.08243 0.05554 1.484 0.137799
## educationsecondary 0.15080 0.05652 2.668 0.007628 **
## educationtertiary 0.31774 0.06570 4.836 1.32e-06 ***
## educationunknown 0.20162 0.09242 2.182 0.029142 *
## defaultyes -0.15693 0.14688 -1.068 0.285331
## housingyes -0.54538 0.03810 -14.315 < 2e-16 ***
## loanyes -0.40800 0.05303 -7.693 1.44e-14 ***
## contacttelephone -0.28124 0.06400 -4.395 1.11e-05 ***
## contactunknown -1.34757 0.06337 -21.264 < 2e-16 ***
## monthaug -0.97790 0.06846 -14.285 < 2e-16 ***
## monthdec 0.57037 0.16198 3.521 0.000430 ***
## monthfeb -0.44687 0.07500 -5.958 2.55e-09 ***
## monthjan -1.08349 0.10619 -10.204 < 2e-16 ***
## monthjul -0.79701 0.06766 -11.780 < 2e-16 ***
## monthjun 0.10827 0.08091 1.338 0.180876
## monthmar 1.06565 0.11027 9.664 < 2e-16 ***
## monthmay -0.50693 0.06341 -7.995 1.30e-15 ***
## monthnov -0.83487 0.07443 -11.216 < 2e-16 ***
## monthoct 0.68169 0.09776 6.973 3.10e-12 ***
## monthsep 0.65424 0.10739 6.092 1.11e-09 ***
## poutcomeother 0.25373 0.07960 3.188 0.001435 **
## poutcomesuccess 2.26564 0.07345 30.848 < 2e-16 ***
## poutcomeunknown 0.03495 0.05155 0.678 0.497806
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 32631 on 45210 degrees of freedom
## Residual deviance: 27296 on 45175 degrees of freedom
## AIC: 27368
##
## Number of Fisher Scoring iterations: 6
X_cat <- model.matrix(model_glm_cat, data = bank_cat)
reference_lvls <- data.frame(
Variable = cat_model_vars,
Reference = sapply(bank_cat[cat_model_vars], function(x) levels(x)[1])
) |> tibble::as_tibble()
reference_lvls
## # A tibble: 9 × 2
## Variable Reference
## <chr> <chr>
## 1 job admin.
## 2 marital divorced
## 3 education primary
## 4 default no
## 5 housing no
## 6 loan no
## 7 contact cellular
## 8 month apr
## 9 poutcome failure
odds_ratios <- data.frame(
Variable = names(coef(glm_cats)),
Odds_Ratio = exp(coef(glm_cats))
) |> dplyr::mutate(Effect = paste0(round((Odds_Ratio - 1) * 100, 1), "%")) |>
dplyr::mutate(Odds_Ratio = round(Odds_Ratio, 3)) |>
dplyr::arrange(desc(Odds_Ratio)) |>
tibble::as_tibble()
odds_ratios
## # A tibble: 36 × 3
## Variable Odds_Ratio Effect
## <chr> <dbl> <chr>
## 1 poutcomesuccess 9.64 863.7%
## 2 monthmar 2.90 190.3%
## 3 monthoct 1.98 97.7%
## 4 monthsep 1.92 92.4%
## 5 monthdec 1.77 76.9%
## 6 jobretired 1.59 59.2%
## 7 jobstudent 1.39 39.2%
## 8 educationtertiary 1.37 37.4%
## 9 poutcomeother 1.29 28.9%
## 10 educationunknown 1.22 22.3%
## # ℹ 26 more rows
We can see from the categorical only variables that:
| Variable | Visual Pattern? | Clear % Difference? | Keep? |
|---|---|---|---|
| contact | yes | yes (cellular > unknown) | yes |
| loan | yes | yes (loan = less likely) | yes |
| housing | yes | yes (housing = likely) | yes |
| default | maybe | some | maybe |
| education | yes | yes (tertiary increases) | yes |
| poutcome | strong | yes (success = very high) | yes |
| marital | maybe | some separation | maybe |
| job | mixed | a few clear signals | maybe (group rare levels) |
Carefully look at poutcome as we do not know what drives from previous mkt approach, and if the customer is showing an affinity to long term deposit, maybe is increasing the current deposit. Default sounds like a good story, I tried swapping ref with not much difference.
We are having very conflicting results based on the multiple explorations on numerical, that is telling us, that we need categorical variables to play a role in the explainability.
We think that cyclical encoding for month as we see some patterns on specific months could help the model to explain better as seasonality seems to have some effect.
| Variable | Type | Reason for Inclusion |
|---|---|---|
| duration | Numerical | Strongest univariate predictor; higher durations consistently increase subscription odds |
| pdays | Numerical | Captures time since last contact; reflects engagement recency |
| previous | Numerical | Reflects past campaign success; useful but may be redundant with pdays/campaign |
| balance | Numerical | Indicates client financial status; moderate predictive signal |
| campaign | Numerical | Current campaign intensity; negative association suggests fatigue with repeated contact |
| month_sin | Numerical | Cyclical encoding of month (seasonality); preserves circular month structure |
| month_cos | Numerical | Complement to month_sin; together capture monthly cyclic patterns |
| contact | Categorical | Clear visual and statistical difference; contact method affects likelihood to subscribe |
| loan | Categorical | Customers with loans are less likely to subscribe; simple and interpretable |
| education | Categorical | Higher education levels (tertiary) correlate with higher subscription odds |
| marital | Categorical | Some variation observed; potentially useful with clear reference level |
| job | Categorical | Certain job roles (retired, student) show increased subscription; use with level grouping |
Will do the cyclical encoding for month and dummy variables (as they are factors GLM will dummy them)
candidate_data <- bank
candidate_data$month_num <- as.numeric(factor(candidate_data$month, levels = c(
"jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec"
)))
candidate_data$month_sin <- sin(2 * pi * candidate_data$month_num / 12)
candidate_data$month_cos <- cos(2 * pi * candidate_data$month_num / 12)
candidate_data <- candidate_data |> dplyr::select(-month)
head(candidate_data)
## age job marital education default balance housing loan contact day
## 1 58 management married tertiary no 2143 yes no unknown 5
## 2 44 technician single secondary no 29 yes no unknown 5
## 3 33 entrepreneur married secondary no 2 yes yes unknown 5
## 4 47 blue-collar married unknown no 1506 yes no unknown 5
## 5 33 unknown single unknown no 1 no no unknown 5
## 6 35 management married tertiary no 231 yes no unknown 5
## duration campaign pdays previous poutcome subscribed month_num month_sin
## 1 261 1 -1 0 unknown no 5 0.5
## 2 151 1 -1 0 unknown no 5 0.5
## 3 76 1 -1 0 unknown no 5 0.5
## 4 92 1 -1 0 unknown no 5 0.5
## 5 198 1 -1 0 unknown no 5 0.5
## 6 139 1 -1 0 unknown no 5 0.5
## month_cos
## 1 -0.8660254
## 2 -0.8660254
## 3 -0.8660254
## 4 -0.8660254
## 5 -0.8660254
## 6 -0.8660254
split_rate <- 0.7
split <- sample(1:nrow(candidate_data), split_rate * nrow(candidate_data))
train_data <- candidate_data[split, ]
test_data <- candidate_data[-split, ]
#num_feat <- c("duration", "poutcome", "pdays", "balance", "default", "housing", "campaign", "month_sin", "month_cos")
num_feat <- c("duration", "poutcome", "balance", "housing", "campaign", "month_sin", "month_cos")
cat_feat <- c("contact", "loan", "education", "marital", "job", "day", "previous")
features <- c(num_feat, cat_feat)
candidate_model <- as.formula(paste("subscribed ~", paste(features, collapse = " + ")))
candidate_fit <- glm(candidate_model, data = train_data, family = binomial)
summary(candidate_fit)
##
## Call:
## glm(formula = candidate_model, family = binomial, data = train_data)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -2.407e+00 1.364e-01 -17.643 < 2e-16 ***
## duration 4.137e-03 7.600e-05 54.432 < 2e-16 ***
## poutcomeother 2.778e-01 1.032e-01 2.691 0.007120 **
## poutcomesuccess 2.329e+00 9.228e-02 25.242 < 2e-16 ***
## poutcomeunknown -2.740e-01 6.852e-02 -3.999 6.37e-05 ***
## balance 1.455e-05 5.938e-06 2.451 0.014256 *
## housingyes -8.250e-01 4.830e-02 -17.082 < 2e-16 ***
## campaign -1.129e-01 1.245e-02 -9.072 < 2e-16 ***
## month_sin 2.001e-01 3.479e-02 5.754 8.74e-09 ***
## month_cos 5.470e-03 3.424e-02 0.160 0.873076
## contacttelephone -8.640e-02 8.697e-02 -0.993 0.320484
## contactunknown -1.224e+00 7.281e-02 -16.809 < 2e-16 ***
## loanyes -6.104e-01 7.154e-02 -8.532 < 2e-16 ***
## educationsecondary 1.292e-01 7.553e-02 1.711 0.087044 .
## educationtertiary 3.799e-01 8.765e-02 4.335 1.46e-05 ***
## educationunknown 2.679e-01 1.201e-01 2.230 0.025735 *
## maritalmarried -1.448e-01 6.922e-02 -2.092 0.036472 *
## maritalsingle 1.157e-01 7.430e-02 1.558 0.119294
## jobblue-collar -3.976e-01 8.561e-02 -4.644 3.41e-06 ***
## jobentrepreneur -5.096e-01 1.521e-01 -3.350 0.000808 ***
## jobhousemaid -7.065e-01 1.673e-01 -4.223 2.41e-05 ***
## jobmanagement -1.862e-01 8.638e-02 -2.155 0.031158 *
## jobretired 3.604e-01 1.017e-01 3.543 0.000396 ***
## jobself-employed -3.537e-01 1.303e-01 -2.715 0.006636 **
## jobservices -3.394e-01 9.953e-02 -3.410 0.000650 ***
## jobstudent 4.980e-01 1.244e-01 4.002 6.28e-05 ***
## jobtechnician -1.755e-01 8.056e-02 -2.179 0.029336 *
## jobunemployed -2.846e-01 1.347e-01 -2.113 0.034572 *
## jobunknown -2.054e-01 2.651e-01 -0.775 0.438595
## day -2.089e-03 2.581e-03 -0.809 0.418447
## previous 4.015e-03 6.456e-03 0.622 0.534035
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 22747 on 31646 degrees of freedom
## Residual deviance: 15633 on 31616 degrees of freedom
## AIC: 15695
##
## Number of Fisher Scoring iterations: 6
threshold <- 0.25
pred <- predict(candidate_fit, newdata = test_data, type = "response")
model_levels <- levels(candidate_data$subscribed)
pred_class <- factor(ifelse(pred > threshold, "yes", "no"), levels = model_levels)
actual <- factor(test_data$subscribed, levels = model_levels)
confusionMatrix(pred_class, actual, positive = "yes")
## Confusion Matrix and Statistics
##
## Reference
## Prediction no yes
## no 11163 717
## yes 791 893
##
## Accuracy : 0.8888
## 95% CI : (0.8834, 0.8941)
## No Information Rate : 0.8813
## P-Value [Acc > NIR] : 0.00330
##
## Kappa : 0.479
##
## Mcnemar's Test P-Value : 0.06013
##
## Sensitivity : 0.55466
## Specificity : 0.93383
## Pos Pred Value : 0.53029
## Neg Pred Value : 0.93965
## Prevalence : 0.11870
## Detection Rate : 0.06584
## Detection Prevalence : 0.12415
## Balanced Accuracy : 0.74424
##
## 'Positive' Class : yes
##
thresholds <- seq(0.1, 0.9, by = 0.01)
metrics_df <- purrr::map_dfr(thresholds, function(thresh) {
pred_class <- factor(ifelse(pred > thresh, "yes", "no"), levels = c("no", "yes"))
tibble(
threshold = thresh,
precision = yardstick::precision_vec(truth = actual, estimate = pred_class, event_level = "second"),
recall = yardstick::recall_vec(truth = actual, estimate = pred_class, event_level = "second"),
f1 = yardstick::f_meas_vec(truth = actual, estimate = pred_class, event_level = "second")
)
})
ggplot(metrics_df, aes(x = threshold)) +
geom_line(aes(y = f1), color = "blue") +
geom_line(aes(y = precision), color = "green") +
geom_line(aes(y = recall), color = "red") +
labs(title = "Threshold Tuning", y = "Metric", x = "Threshold")
test_data_aug <- test_data %>%
dplyr::mutate(
pred_prob = pred,
pred_class = factor(ifelse(pred > threshold, "yes", "no"), levels = c("no", "yes")),
subscribed = factor(subscribed, levels = c("no", "yes")),
result = case_when(
subscribed == "yes" & pred_class == "yes" ~ "TP",
subscribed == "no" & pred_class == "yes" ~ "FP",
subscribed == "yes" & pred_class == "no" ~ "FN",
subscribed == "no" & pred_class == "no" ~ "TN"
)
)
ggplot(test_data_aug, aes(x = duration, y = balance, color = result)) +
geom_point(alpha = 0.4) +
labs(title = "False Positives vs. True Positives",
subtitle = paste("Threshold:", threshold),
color = "Prediction Outcome")
test_data$subscribed <- factor(test_data$subscribed, levels = c("no", "yes"))
pr_df <- tibble(
subscribed = test_data$subscribed,
.pred_yes = pred
)
pr_curve(pr_df, truth = subscribed, .pred_yes) %>%
autoplot() +
labs(
title = "Precision-Recall Curve",
subtitle = "Probability thresholds for predicting 'yes'"
)